<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/10/30
 * Time: 下午1:50
 */

namespace App\Models;

use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;
use Yansongda\Pay\Pay as YSpay;

class Pay extends Model
{
    protected $table = 'pay';

    public $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function MobilerechargeOrder()
    {
        return $this->hasOne(MobileRechargeOrder::class);
    }

    public function rechargeOrder()
    {
        return $this->hasOne(RechargeOrder::class);
    }
     public static function setPaid(Pay $pay)
     {
        try{
            DB::beginTransaction();
            //修改支付信息
            $pay->is_paid = 1;
            $pay->paid_at = Carbon::now();
            $pay->save();
            //获取订单信息
            $order = $pay->rechargeOrder;
            //判断订单是否存在
            if ($order){
                //修改订单状态
                $order->status = RechargeOrder::STATUS_PAID;
                $order->paid_at = Carbon::now();
                $order->save();
                //判断是否使用优惠,使用则修改优惠券状态
                if ($order->coupon_id>0){
                    //查询优惠券信息
                    $coupon = UserCoupon::query()->where("id",$order->coupon_id)->first();
                    $coupon->status = 2;
                    $coupon->save();
                }
                //判断充值类型,1--套餐充值
                if ($order->type==RechargeOrder::TYPE_RECHARGE){
                    //遍历充值期数
                    for ($i = 1; $i <= $order->months; $i++) {
                        if ($order->months==1 && $i == 1) {
                            $payAt = Carbon::parse('+1 months')->toDateTimeString();// 一个月套餐充值
                        } else {
                            $payAt = Carbon::now()->addMonths($i-1)->toDateTimeString();// N个月套餐充值
                        }
                        //新增充值详情数据
                        $detail = new RechargeOrderDetail();
                        $detail->recharge_order_id = $order->id;
                        $detail->current_month = $i;
                        $detail->total_month = $order->months;
                        $detail->user_id = $order->user_id;
                        $detail->oil_card_id = $order->oil_card_id;
                        $detail->amount = $order->recharge_amount;
                        $detail->pay_at = $payAt;
                        $detail->recharge_mode = $order->recharge_mode;
                        $detail->save();
                        // 创建充值任务
                        RechargeTask::createTask($order->oilCard, $detail->amount, $payAt, $order->id, $order->user_id , $order->recharge_mode, $detail->id);

                    }
                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->pending_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->save();
                }else{
                    // 创建充值任务
                    $payAt = Carbon::now()->toDateTimeString();
                    // 创建充值任务
                    RechargeTask::createTask($order->oilCard, $order->recharge_amount, $payAt, $order->id, $order->user_id , $order->recharge_mode, $order->id);
                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount);
                    $order->user->pending_amount += (float) ($order->recharge_amount);
                    $order->user->save();
                }

                //修改领取油卡物流信息
                $shopOrder = ShopOrder::find($order->shop_order_id);
                if ($shopOrder){
                    $shopOrder->order_status = 1;
                    $shopOrder->pay_id = $pay->id;
                    $shopOrder->pay_time = Carbon::now();
                    $shopOrder->save();
                }

                //绑定油卡
                $shopOrder = ShopOrder::query()->where("id",$order->shop_order_id)->first();
                if ($shopOrder){
                    //查询油卡
                    $oilCardData = OilCard::query()->where("id",$order->oil_card_id)->first();
                    if ($oilCardData){
                        $oilCardData->status = 1;
                        $oilCardData->save();
                    }
                }

                //修改销售数量
                if ($pay->rechargeOrder->recharge_id!=0){
                    $recharge = Recharge::find($pay->rechargeOrder->recharge_id);
                    $recharge->sell_num = $recharge->sell_num+mt_rand(1,$recharge->months);
                    $recharge->save();
                }
            }
            DB::commit();
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            throw new \Exception('订单支付出错啦');
        }
     }

    public static function setPaids(Pay $pay)
    {
        DB::beginTransaction();
        try {
            $pay->is_paid = 1;
            $pay->paid_at = Carbon::now()->toDateTimeString();
            $pay->save();

            //首次充值赠送88元优惠券
            $order = $pay->rechargeOrder;
            /*
            $user = DB::table('recharge_order')->where('status','>',0)->where('user_id',$order->user_id)->get();
            if ($user->count() == 0){
                $regCouponIds = Configure::rechargeCoupon();
                if ($regCouponIds) {
                    foreach ($regCouponIds as $couponId) {
                        UserCoupon::sendToUser($couponId, $order->user_id);
                    }
                }
            }
            */

            if ($pay->rechargeOrder) {
                $order->status  = RechargeOrder::STATUS_PAID;
                $order->paid_at = Carbon::now()->toDateTimeString();
                $order->save();
                //成功支付后修改优惠券状态
                DB::update('update yk_user_coupon set status = 2 where id = ?', [$order->coupon_id]);

                // 生成充值明细
                if ($order->type == RechargeOrder::TYPE_RECHARGE) {
                    for ($i = 1; $i <= $order->months; $i++) {
                        if ($order->months==1 && $i == 1) {
                            $payAt = Carbon::parse('+1 months')->toDateTimeString();// 一个月套餐充值
                        } else {
                            $payAt = Carbon::now()->addMonths($i-1)->toDateTimeString();// N个月套餐充值
                        }

                        $detail = RechargeOrderDetail::create([
                            'recharge_order_id' => $order->id,
                            'current_month'     => $i,
                            'total_month'       => $order->months,
                            'user_id'           => $order->user_id,
                            'oil_card_id'       => $order->oil_card_id,
                            'amount'            => $order->recharge_amount,
                            'pay_at'            => $payAt,
                            'recharge_mode'     => $order->recharge_mode
                        ]);
                        $shopOrder = ShopOrder::query()->where("order_sn",$order->order_sn)->first();
                        if ($shopOrder){
                            $shopOrder->order_status = 1;
                            $shopOrder->pay_id = $pay->id;
                            $shopOrder->pay_time = Carbon::now();
                            $shopOrder->save();
                            $recharge_mode = 2;
                        }else{
                            $recharge_mode = $order->recharge_mode;
                        }
                        // 创建充值任务
                        RechargeTask::createTask($order->oilCard, $detail->amount, $payAt, $order->id, $order->user_id , $recharge_mode, $detail->id);

                    }

                    $recharge_amount = $order->recharge_amount * $order->months;

                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->pending_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->save();
                } else {
                    // 创建充值任务
                    $payAt = Carbon::now()->toDateTimeString();
                    $shopOrder = ShopOrder::query()->where("order_sn",$order->order_sn)->first();
                    if ($shopOrder){
                        $shopOrder->order_status = 1;
                        $shopOrder->pay_id = $pay->id;
                        $shopOrder->pay_time = Carbon::now();
                        $shopOrder->save();
                        $recharge_mode = 2;
                    }else{
                        $recharge_mode = $order->recharge_mode;
                    }
                    // 创建充值任务
                    RechargeTask::createTask($order->oilCard, $order->recharge_amount, $payAt, $order->id, $order->user_id , $recharge_mode, $order->id);
                    $recharge_amount = $order->recharge_amount;
                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount);
                    $order->user->pending_amount += (float) ($order->recharge_amount);
                    $order->user->save();
                }


                //绑定油卡
                $shopOrder = ShopOrder::find($order->shop_order_id);
                if ($shopOrder){
                    $shopOrder->order_status = 2;
                    $shopOrder->save();
                    //查询油卡
                    $oilCardData = OilCard::query()->where("id",$order->oil_card_id)->first();
                    if ($oilCardData){
                        $oilCardData->status = 1;
                        $oilCardData->save();
                    }
                }

                //修改销售数量
                if ($pay->rechargeOrder->recharge_id!=0){
                    $recharge = Recharge::find($pay->rechargeOrder->recharge_id);
                    $recharge->sell_num = $recharge->sell_num+mt_rand(1,$recharge->months);
                    $recharge->save();
                }

            }

            DB::commit();

        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            throw new \Exception('订单支付出错啦');
        }
    }


    //话费充值
    public static function setPaid_two(Pay $pay)
    {
        DB::beginTransaction();
        try {

            $pay->is_paid = 1;
            $pay->paid_at = Carbon::now()->toDateTimeString();
            $pay->save();

            $order = $pay->MobilerechargeOrder;
            if ($pay->MobilerechargeOrder) {
                $order->status  = MobileRechargeOrder::STATUS_PAID;
                $order->paid_at = Carbon::now()->toDateTimeString();
                $order->save();
            }

            //成功支付后修改优惠券状态
            DB::update('update yk_user_coupon set status = 2 where id = ?', [$order->coupon_id]);

            // 生成充值明细
            if ($order->type == MobileRechargeOrder::TYPE_RECHARGE) {
                for ($i = 1; $i <= $order->months; $i++) {
                    if ($order->months==1 && $i == 1) {
                        $payAt = Carbon::parse('+1 months')->toDateTimeString();// 一个月套餐充值
                    } else {
                        $payAt = Carbon::now()->addMonths($i-1)->toDateTimeString();// N个月套餐充值
                    }


                    $detail = MobileRechargeOrderDetail::create([
                        'recharge_order_id' => $order->id,
                        'current_month'     => $i,
                        'total_month'       => $order->months,
                        'user_id'           => $order->user_id,
                        'amount'            => $order->recharge_amount,
                        'mobile'            => $order->mobile,
                        'pay_at'            => Carbon::now()
                    ]);
                    // 创建充值任务
                    MobileRechargeTask::createTask($order->mobile,$detail->amount,$payAt, $order->id, $detail->id);
                }
            }else{
                $payAt = Carbon::now()->toDateTimeString();
                MobileRechargeTask::createTask($order->mobile,$order->recharge_amount,$payAt, $order->id,0);
            }
            DB::commit();

        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            //throw new \Exception('订单支付出错啦');
        }
    }


    public static function alipay(Pay $pay)
    {
        // 创建支付单。
//        $alipay = app('alipay.mobile');
//        $alipay->setOutTradeNo($pay->pay_sn);
//        $alipay->setTotalFee($pay->amount);
//        $alipay->setSubject('充值订单');
//        $alipay->setBody('订单支付'. $pay->amount . '元');
//
//        // 返回签名后的支付参数给支付宝移动端的SDK。
//        return $alipay->getPayPara();
        $order = [
            'out_trade_no' => $pay->pay_sn,
            'total_amount' => $pay->amount,
            'subject' => '充值订单',
        ];
        $alipay = YSpay::alipay(config('pay.alipay'))->app($order);
        return $alipay->getContent();
    }

    public static function weixinApp(Pay $pay)
    {
        $app = Factory::payment(config('wechat.app_pay'));

        $result = $app->order->unify([
            'body' => '订单支付'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'APP', // 请对应换成你的支付方式对应的值类型
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->appConfig($result['prepay_id']);
        }
        return $result;
    }

    public static function weixin(Pay $pay, $openId)
    {
        $app = Factory::payment(config('wechat.wx_pay'));
        $result = $app->order->unify([
            'body' => '订单支付'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openId,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->bridgeConfig($result['prepay_id']);
        }
        return $result;
    }

    /**
     * 油卡支付
     * @param Pay $pay
     * @return mixed
     */
    public static function alipay_num(Pay $pay)
    {
        $order = [
            'out_trade_no' => $pay->pay_sn,
            'total_amount' => $pay->amount,
            'subject' => '充值订单',
        ];
        $alipay = YSpay::alipay(config('pay.alipay'))->app($order);

        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $shuffled_two = $shuffled.$pay->pay_sn;
        DB::table('pay')->where('id', $pay->id)->update(['str_sn' => $shuffled_two]);
        // 返回签名后的支付参数给支付宝移动端的SDK。
        return $alipay->getContent();
    }

    /**
     * 油卡支付
     * @param Pay $pay
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    public static function weixinApp_num(Pay $pay)
    {
        $app = Factory::payment(config('wechat.app_pay'));
        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $shuffled_two = $shuffled.$pay->pay_sn;
        DB::table('pay')->where('id', $pay->id)->update(['str_sn' => $shuffled_two]);
        $result = $app->order->unify([
            'body' => '订单支付'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'APP', // 请对应换成你的支付方式对应的值类型
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->appConfig($result['prepay_id']);
        }
        return $result;
    }

    /**
     * 油卡支付
     * @param Pay $pay
     * @param $openId
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function weixin_num(Pay $pay, $openId)
    {
        $app = Factory::payment(config('wechat.wx_pay'));
        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $shuffled_two = $shuffled.$pay->pay_sn;
        DB::table('pay')->where('id', $pay->id)->update(['str_sn' => $shuffled_two]);
        $result = $app->order->unify([
            'body' => '订单支付'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openId,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->bridgeConfig($result['prepay_id']);
        }
        return $result;
    }


    /**
     * 话费支付
     * @param Pay $pay
     * @return mixed
     */
    public static function alipay_number(Pay $pay)
    {
        $key = 'huafei';
        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $shuffled_two = $key.$shuffled.$pay->pay_sn;
        // 创建支付单。
        $alipay = app('alipay.mobile');
        $alipay->setOutTradeNo($pay->pay_sn);
        $alipay->setTotalFee($pay->amount);
        $alipay->setSubject('充值订单');
        $alipay->setBody('订单支付'. $pay->amount . '元');

        DB::table('pay')->where('id', $pay->id)->update(['str_sn' => $shuffled_two]);
        // 返回签名后的支付参数给支付宝移动端的SDK。
        return $alipay->getPayPara();
    }

    /**
     * 话费支付
     * @param Pay $pay
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    public static function weixinApp_number(Pay $pay)
    {
        $app = Factory::payment(config('wechat.app_pay'));
        $key = 'huafei';
        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $shuffled_two = $key.$shuffled.$pay->pay_sn;
        DB::table('pay')->where('id', $pay->id)->update(['str_sn' => $shuffled_two]);
        $result = $app->order->unify([
            'body' => '充值订单'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'APP', // 请对应换成你的支付方式对应的值类型
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->appConfig($result['prepay_id']);
        }
        return $result;
    }

    /**
     * 话费支付
     * @param Pay $pay
     * @param $openId
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    public static function weixin_number(Pay $pay, $openId)
    {
        $app = Factory::payment(config('wechat.wx_pay'));
        $key = 'huafei';
        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $shuffled_two = $key.$shuffled.$pay->pay_sn;
        DB::table('pay')->where('id', $pay->id)->update(['str_sn' => $shuffled_two]);
        $result = $app->order->unify([
            'body' => '充值订单'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openId,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->bridgeConfig($result['prepay_id']);
        }
        return $result;
    }


    public static function makeYouKaPaySN()
    {
        return 'YK' . date('YmdHis') . Str::random(4);
    }

    public static function makeHuaFeiPaySN()
    {
        return 'HF' . date('YmdHis') . Str::random(4);
    }

    public static function makeGouwuPaySn(){
        return 'SH'.date('YmdHis').Str::random(4);
    }

    /**
     *
     * @param $pay_sn
     * @return bool
     */
    public static function isYouKaOrder($pay_sn)
    {
        return strpos($pay_sn,'YK') === 0 ? true : false;
    }

    /**
     *
     * @param $pay_sn
     * @return bool
     */
    public static function isHuaFeiOrder($pay_sn)
    {
        return strpos($pay_sn,'HF') === 0 ? true : false;
    }
}